package com.whc.gulimall.scekill.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.whc.common.to.mq.SecKillTO;
import com.whc.common.utils.R;
import com.whc.gulimall.scekill.dto.SecKillSkuDTO;
import com.whc.gulimall.scekill.dto.SeckillSessionDTO;
import com.whc.gulimall.scekill.dto.SeckillSkuRelationDTO;
import com.whc.gulimall.scekill.dto.SkuInfoDTO;
import com.whc.gulimall.scekill.feign.CouponFeignService;
import com.whc.gulimall.scekill.feign.ProductFeignService;
import com.whc.gulimall.scekill.interceptor.SecKillInterceptor;
import com.whc.gulimall.scekill.service.SecKillService;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author angaoen
 */
@Service
public class SecKillServiceImpl implements SecKillService {

    @Resource
    private CouponFeignService couponFeignService;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @Resource
    private ProductFeignService productFeignService;

    private final String SESSION_CACHE_PREFIX = "seckill:session:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:sku";

    private final String SKU_STOCK_SEMAPHORE = "sku:stock:";

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private ThreadPoolExecutor executors;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 上架近三天的秒杀商品
     */
    @Override
    public void upSecKillProductOfThreeDays() throws ExecutionException, InterruptedException {
        R r = couponFeignService.listLastThreeDaysSession();
        if (Objects.equals(r.getCode(), 0)) {
            List<SeckillSessionDTO> data = r.getData(new TypeReference<List<SeckillSessionDTO>>() {
            });
            if (CollUtil.isNotEmpty(data)) {
                CompletableFuture<Void> sessionTask = CompletableFuture
                        .runAsync(() -> saveSessionsInfo(data), executors);
                CompletableFuture<Void> skuInfoTask = CompletableFuture
                        .runAsync(() -> saveSessionSkuInfo(data), executors);

                CompletableFuture.allOf(sessionTask, skuInfoTask).get();
            }
        }
    }

    /**
     * 获取最近秒杀的商品信息
     *
     * @return 最近秒杀的商品信息
     */
    @Override
    public List<SecKillSkuDTO> listSecKillInfo() {
        // 获取当前时间
        long currentTime = System.currentTimeMillis();
        // 获取所有的场次key
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        if (CollUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                if (StrUtil.isNotBlank(key)) {
                    // 分割key，获取开始时间和结束时间
                    String[] dateArray = key.replace(SESSION_CACHE_PREFIX, "").split("_");
                    long startLong = Long.parseLong(dateArray[0]);
                    long endLong = Long.parseLong(dateArray[1]);
                    // 如果在活动期限之内
                    if (currentTime >= startLong && currentTime < endLong) {
                        // 获取相应key下的所有秒杀商品key
                        List<String> skuKey = redisTemplate.opsForList().range(key, 0, -1);
                        if (CollUtil.isNotEmpty(skuKey)) {
                            BoundHashOperations<String, String, String> hashOps =
                                    redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                            // 通过秒杀商品key获取到秒杀商品数据
                            List<String> list = hashOps.multiGet(skuKey);
                            if (CollUtil.isNotEmpty(list)) {
                                // 封装数据
                                return list.stream().map(item -> JSON.parseObject(item, SecKillSkuDTO.class))
                                        .collect(Collectors.toList());
                            }
                        }
                        break;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 通过skuId获取到sku在redis秒杀中的信息
     *
     * @param skuId skuId
     * @return sku在redis秒杀中的信息
     */
    @Override
    public SecKillSkuDTO getSkuInfoBySkuId(Long skuId) {
        // 获取当前时间
        long currentTime = System.currentTimeMillis();
        // 获取所有的场次key
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        if (CollUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                if (StrUtil.isNotBlank(key)) {
                    // 分割key，获取开始时间和结束时间
                    String[] dateArray = key.replace(SESSION_CACHE_PREFIX, "").split("_");
                    long startLong = Long.parseLong(dateArray[0]);
                    long endLong = Long.parseLong(dateArray[1]);
                    // 如果在活动期限之内
                    if (currentTime >= startLong && currentTime < endLong) {
                        // 获取相应key下的所有秒杀商品key
                        List<String> skuKey = redisTemplate.opsForList().range(key, 0, -1);
                        if (CollUtil.isNotEmpty(skuKey)) {
                            BoundHashOperations<String, String, String> hashOps = redisTemplate
                                    .boundHashOps(SKUKILL_CACHE_PREFIX);
                            for (String code : skuKey) {
                                if (ReUtil.isMatch("\\d_" + skuId, code)) {
                                    String json = hashOps.get(code);
                                    if (StrUtil.isNotBlank(json)) {
                                        return JSON.parseObject(json, SecKillSkuDTO.class);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 秒杀商品
     *
     * @param killId     skuId_promotionSessionId
     * @param randomCode 随机码
     * @param num        抢购书
     * @return 订单号
     */
    @Override
    public String kill(String killId, String randomCode, Integer num) {
        // 判断抢购的商品是否在活动范围内
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        String jsonObj = hashOps.get(killId);
        if (StrUtil.isNotBlank(jsonObj)) {
            SecKillSkuDTO secKillSkuDTO = JSON.parseObject(jsonObj, new TypeReference<SecKillSkuDTO>() {
            });
            if (ObjectUtil.isNotNull(secKillSkuDTO)) {
                long currentTimeMillis = System.currentTimeMillis();
                // 在时效范围内
                if (secKillSkuDTO.getStartTime().getTime() <= currentTimeMillis
                        && secKillSkuDTO.getEndTime().getTime() > currentTimeMillis) {
                    // 校验随机码和商品id
                    if (randomCode.equals(secKillSkuDTO.getRandomCode())
                            && killId.equals(secKillSkuDTO.getPromotionSessionId() + "_" + secKillSkuDTO.getSkuId())) {
                        // 抢购数量是否合理
                        if (num <= secKillSkuDTO.getSeckillLimit()) {
                            // 设置占位符，userId_promotionSessionId_skuId
                            Boolean flag = redisTemplate.opsForValue()
                                    .setIfAbsent(SecKillInterceptor.threadLocal.get().getId()
                                                    + "_" + secKillSkuDTO.getPromotionSessionId()
                                                    + "_" + secKillSkuDTO.getSkuId(), num.toString(),
                                            secKillSkuDTO.getEndTime().getTime() - currentTimeMillis,
                                            TimeUnit.MILLISECONDS);
                            if (Boolean.TRUE.equals(flag)) {
                                // 如果获得了许可证，则为true；如果在获得许可证之前等待时间已过，则为false。
                                flag = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode)
                                        .tryAcquire(num);
                                if (flag) {
                                    String orderSn = IdWorker.getTimeId();
                                    SecKillTO to = new SecKillTO();
                                    to.setOrderSn(orderSn);
                                    to.setNum(num);
                                    to.setPromotionSessionId(secKillSkuDTO.getPromotionSessionId());
                                    to.setSkuId(secKillSkuDTO.getSkuId());
                                    to.setMemberId(SecKillInterceptor.threadLocal.get().getId());
                                    to.setSeckillPrice(secKillSkuDTO.getSeckillPrice());
                                    // 通知消息队列
                                    rabbitTemplate.convertAndSend("order-event-exchange",
                                            "order.seckill.order", to);
                                    return orderSn;
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    private void saveSessionSkuInfo(List<SeckillSessionDTO> data) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        // 获取到所有的skuId
        HashSet<Long> skuSet = new HashSet<>(data.size());
        for (SeckillSessionDTO dto : data) {
            skuSet.addAll(dto.getRelationEntities().stream()
                    .map(item -> Boolean.TRUE.equals(hashOps.hasKey(item.getPromotionSessionId()
                            + "_" + item.getSkuId()))
                            ? null
                            : item.getSkuId()).filter(Objects::nonNull).collect(Collectors.toList()));
        }
        // 通过skuId获取所有的sku信息
        if (CollUtil.isNotEmpty(skuSet)) {
            List<Long> skuIdList = new ArrayList<>(skuSet);
            R r = productFeignService.listSkuInfoBySkuIds(skuIdList);
            Map<Long, SkuInfoDTO> skuInfoMap = null;
            if (Objects.equals(r.getCode(), 0)) {
                List<SkuInfoDTO> skuInfoList = r.getData(new TypeReference<List<SkuInfoDTO>>() {
                });
                skuInfoMap = skuInfoList.stream()
                        .collect(Collectors.toMap(SkuInfoDTO::getSkuId, item -> item));
            }
            Map<String, String> dataMap = new HashMap<>(data.size());
            for (SeckillSessionDTO dto : data) {
                for (SeckillSkuRelationDTO relationEntity : dto.getRelationEntities()) {
                    // 只有redis中没有相应skuId的数据，存放才有意义
                    if (Boolean.FALSE.equals(hashOps.hasKey(relationEntity.getPromotionSessionId()
                            + "_" + relationEntity.getSkuId()))) {
                        // 设置属性
                        SecKillSkuDTO secKillSkuDTO = new SecKillSkuDTO();
                        secKillSkuDTO.setStartTime(dto.getStartTime());
                        Date endTime = dto.getEndTime();
                        secKillSkuDTO.setEndTime(endTime);
                        // 属性对拷
                        BeanUtil.copyProperties(relationEntity, secKillSkuDTO);
                        if (CollUtil.isNotEmpty(skuInfoMap)) {
                            secKillSkuDTO.setSkuInfoDTO(skuInfoMap.get(secKillSkuDTO.getSkuId()));
                        }
                        // 生成随机码
                        String randomCode = UUID.fastUUID().toString().replace("-", "");
                        secKillSkuDTO.setRandomCode(randomCode);

                        // 创建信号量
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                        semaphore.trySetPermits(relationEntity.getSeckillCount().intValue());
                        redisTemplate.expire(SKU_STOCK_SEMAPHORE + randomCode,
                                endTime.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);

                        // 在库存中，锁定对应商品数

                        dataMap.put(relationEntity.getPromotionSessionId()
                                + "_" + relationEntity.getSkuId(), JSON.toJSONString(secKillSkuDTO));
                    }
                }
            }
            // 把数据存入redis中
            hashOps.putAll(dataMap);
        }


    }

    /**
     * 保存场次和场次包含的sku列表信息
     *
     * @param data 场次信息
     */
    private void saveSessionsInfo(List<SeckillSessionDTO> data) {
        ListOperations<String, String> ops = redisTemplate.opsForList();
        // 缓存到redis
        for (SeckillSessionDTO dto : data) {
            long endTime = dto.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + dto.getCreateTime().getTime() + "_" + endTime;
            // 判断redis中是否已经保存对应key的数据
            if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
                ops.leftPushAll(key, dto.getRelationEntities().stream().map(item -> item.getPromotionSessionId()
                                + "_" + item.getSkuId())
                        .collect(Collectors.toList()));
                // 设置key的过期时间
                ops.getOperations().expire(key, endTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
            }
        }
    }
}
